package com.hqj.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hqj.service.OssService;
import com.hqj.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author 黄啟军
 * @version 1.0
 * @date 2020/7/19 0019
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadOssFile(MultipartFile file)  {
        // 工具类赋值
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try{
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String filename = file.getOriginalFilename();
            //1.在文件名称里面添加随时唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //拼接文件名
            filename = uuid +filename;
            //2.文件分类存储
            //工具类的使用--处理时间格式
            String folder = new DateTime().toString("yyyy/MM/dd");
            filename = "shijuan/"+folder+"/"+filename;
            //调用OSS方法实现上传<yourObjectName>：aa/bb/文件名文件夹名称inputStream上传文件输入流
            ossClient.putObject(bucketName, filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //返回上传后的文件名
            //https://com-hqj-oss.oss-cn-beijing.aliyuncs.com/jiaoyou.png
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
